﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


[AddComponentMenu("UI/Extensions/GUIWidgets/Effects/FlipBook")]
public class FlipBook : MonoBehaviour {

	public Sprite[] animateSprites;
	public float animateFPS = 12f;
	public bool playOnAwake = true;
	public bool animateLoop = true;
	public bool ignoreTimeScale = true;
	public bool autoSetNativeSize = false;

	protected Image _image;
	protected SpriteRenderer _spriteRenderer;
	protected float _animateTick = 0f;
	protected float _animateTimer = 0f;
	protected int _spriteIndex = 0;
	protected bool _playStoped = true;

	public void Play () {
		_playStoped = false;
		_animateTimer = 0f;

		_spriteIndex = 0;
		DrawSprite();
	}

	public void Stop () {
		_playStoped = true;
	}

	protected void DrawSprite () {
		if (_image != null) {
			_image.overrideSprite = animateSprites [_spriteIndex];

			if (autoSetNativeSize == true)
				_image.SetNativeSize ();
		}
		else {
			_spriteRenderer.sprite = animateSprites [_spriteIndex];
		}
	}

	void OnEnable () {
		_image = GetComponent<Image> ();
		if (_image == null)
			_spriteRenderer = GetComponent<SpriteRenderer>();

		_animateTick = 1.0f / animateFPS;

		UnityEngine.Assertions.Assert.IsTrue (_image != null || _spriteRenderer != null);
		UnityEngine.Assertions.Assert.IsNotNull (animateSprites);
		UnityEngine.Assertions.Assert.IsTrue (animateSprites.Length > 0);

		if (playOnAwake == true)
			Play ();
	}

	void OnDisable () {
		Stop ();
	}

	void Update () {
		if (_playStoped == true || 
			(_image != null && _image.enabled == false) ||
			(_spriteRenderer != null && _spriteRenderer == false))
			return;

		if (ignoreTimeScale == true)
			_animateTimer += Time.unscaledDeltaTime;
		else
			_animateTimer += Time.deltaTime;

		while (_animateTimer >= _animateTick) {
			_animateTimer -= _animateTick;

			_spriteIndex++;
			if (_spriteIndex < animateSprites.Length) {
				DrawSprite();
			} else {
				if (animateLoop == true) {
					_spriteIndex -= animateSprites.Length;

					DrawSprite();
				} else {
					Stop ();
					break;
				}
			}
		}
	}

}
